#!/usr/bin/env python
import gammu
import threading
from Sms import *


class SmsReciver(threading.Thread):
    def __init__(self, stateMachine, inQueue):
	threading.Thread.__init__(self)
    	self._stateMachine = stateMachine
	self._inQueue = inQueue
    def getSmsList(self):
	status = self._stateMachine.GetSMSStatus()
	remain = status['SIMUsed'] + status['PhoneUsed']
	start = True
	smsList = []
	locationList = []
	while remain > 0:
	    if start:
		sms = self._stateMachine.GetNextSMS(Start = True, Folder = 0)
		start = False
	    else:
		sms = self._stateMachine.GetNextSMS\
			(Location = sms[0]['Location'], Folder = 0)
	    remain = remain - len(sms)

	    for m in sms:
		if m['State']=="UnRead":
		    print "state: ", m['State']
		    s = Sms(m['Number'], m['Text'])
		    try:
			# check if sms is syntax friendly; if not leave it
			s.getSurveyId()
			smsList.append(s)
			locationList.append(m['Location'])
		    except Exception, e:
			# sms not syntax friendly
			# print "SmsReciver: ", e
			pass
		
	self._removeSmsFromMemory(locationList)
	return smsList
    def _removeSmsFromMemory(self, locationList):
	#print "removing recived smses:"
	for location in locationList:
	    print "\tdadleting sms number", location
	    self._stateMachine.DeleteSMS(0, location)
    def run(self):
	print "SmsReciver: running"
	while 1:
	    smsList = self.getSmsList()
	    for msg in smsList:
		self._inQueue.put(msg)


def main():
    sm = gammu.StateMachine()
    sm.ReadConfig()
    sm.Init()
    smsReciver = SmsReciver(sm, None)
    smsList = smsReciver.getSmsList()
    print "new messages: ", len(smsList), "\n--"
    for msg in smsList:
	print msg

if __name__=="__main__":
    main()

